package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.dto.NursingPlanDto;
import com.zzyl.serve.mapper.NursingPlanMapper;

import com.zzyl.serve.mapper.NursingProjectPlanMapper;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 护理计划Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-27
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper,NursingPlan>  implements INursingPlanService
{
    private static final String CACHE_KEY_PLAN = "plan:all";
    @Autowired
    private NursingPlanMapper nursingPlanMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询护理计划（根据id查询）
     * 
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id)
    {
        //查询护理计划
        NursingPlan plan = this.getById(id);
        NursingPlanVo vo = new NursingPlanVo();
        BeanUtils.copyProperties(plan, vo);

        //查询护理计划关联的关系数据
        List<NursingProjectPlan> nursingProjectPlans = nursingProjectPlanMapper.selectList(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, id));

        List<NursingProjectPlanVo> nursingProjectPlanVoList = nursingProjectPlans.stream().map(x -> {
            NursingProjectPlanVo nursingProjectPlanVo = new NursingProjectPlanVo();
            BeanUtils.copyProperties(x, nursingProjectPlanVo);
            nursingProjectPlanVo.setExecuteCycle(x.getExecuteCycle().toString());//字符串类型，方便前端回显
            return nursingProjectPlanVo;
        }).collect(Collectors.toList());
        vo.setProjectPlans(nursingProjectPlanVoList);

        return vo;
    }

    /**
     * 查询护理计划列表(分页）
     * 
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan)
    {
        return getBaseMapper().selectNursingPlanList(nursingPlan);
    }

    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;

    /**
     * 新增护理计划
     * 
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertNursingPlan(NursingPlanDto dto)
    {
        //拷贝对象
        NursingPlan plan = new NursingPlan();
        BeanUtils.copyProperties(dto, plan);
        plan.setCreateTime(DateUtils.getNowDate());
        boolean flag = this.save(plan);

        //保存护理项目列表
        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();
        //如果护理项目列表非空，批量保存
        if(CollectionUtils.isNotEmpty(projectPlans)) {
            projectPlans.forEach(x->{
                x.setPlanId(plan.getId());
                x.setCreateTime(DateUtils.getNowDate());
            });
            //批量保存  护理项目
            int num = nursingProjectPlanMapper.batchInsert(projectPlans);
            //判断批量保存结果,如果小于等于0，就说明没有成功
            if (num > 0) {
                flag = true;
            } else {
                flag = false;
            }
        }
        redisTemplate.delete(CACHE_KEY_PLAN);

        return flag?1:0;
    }

    /**
     * 修改护理计划
     * 
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional
    @Override
    public int updateNursingPlan(NursingPlanDto dto)
    {
        //拷贝对象
        NursingPlan plan = new NursingPlan();
        BeanUtils.copyProperties(dto,plan);

        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();

        //如果护理项目列表非空，删除旧关系，批量保存新关系
        if(CollectionUtils.isNotEmpty(projectPlans)) {
            nursingProjectPlanMapper.delete(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId,plan.getId()));
            projectPlans.forEach(x->{
                x.setPlanId(plan.getId());
                x.setCreateTime(DateUtils.getNowDate());
            });
            nursingProjectPlanMapper.batchInsert(projectPlans);
        }
        boolean flag = this.updateById(plan);
        redisTemplate.delete(CACHE_KEY_PLAN);
        //不管护理项目列表是否为空，都更新护理计划
        return  flag? 1 : 0;
    }

    /**
     * 批量删除护理计划
     * 
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteNursingPlanByIds(Long[] ids)
    {
        //删除关联数据
        for (Long id : ids) {
            nursingProjectPlanMapper.delete(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId,id));
        }

        //删除护理计划数据
        redisTemplate.delete(CACHE_KEY_PLAN);
        boolean flag = this.removeByIds(Arrays.asList(ids));
        return flag?1:0;
    }

    /**
     * 删除护理计划信息
     * 
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Long id)
    {
        boolean flag = this.removeById(id);
        redisTemplate.delete(CACHE_KEY_PLAN);
        return flag?1:0;
    }

    /**
     * 查询全部护理计划列表
     *
     * @return
     */
    @Override
    public List<NursingPlanVo> getAll() {
        List<NursingPlanVo> nursingPlanVoList = (List<NursingPlanVo>) redisTemplate.opsForValue().get(CACHE_KEY_PLAN);

        if (!CollectionUtils.isEmpty(nursingPlanVoList)){
            return nursingPlanVoList;
        }

        //查询全部
        List<NursingPlan> nursingPlanList = this.lambdaQuery().select(NursingPlan::getPlanName,NursingPlan::getId).list();
        //封装数据
        List<NursingPlanVo> voList = nursingPlanList.stream().map(x -> {
            NursingPlanVo vo = new NursingPlanVo();
            vo.setLabel(x.getPlanName());
            vo.setId(x.getId());
            vo.setPlanName(x.getPlanName());
            vo.setValue(x.getId().intValue());
            return vo;
        }).collect(Collectors.toList());
        //把从数据库中查出来的数据缓存起来
        redisTemplate.opsForValue().set(CACHE_KEY_PLAN,voList);

        return voList;
    }


}
